<template>
  <div class="business-scenarios-container">
    <div class="page-header">
      <h2>业务场景库</h2>
      <el-button type="primary" @click="createScenario">
        <el-icon>
          <Plus />
        </el-icon>添加场景
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <search-form v-model="searchForm" :loading="loading" @search="handleSearch" @reset="handleReset">
      <el-form-item label="场景名称">
        <el-input v-model="searchForm.scene_name" placeholder="请输入场景名称" clearable />
      </el-form-item>
    </search-form>

    <!-- 场景类型选项卡 -->
    <scenario-card-list :scenarios="scenarios" @view-scenario="viewScenarioHandler" />

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="pageSize"
        :current-page="page" :page-sizes="[10, 20, 50, 100]" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 场景详情对话框 -->
    <el-dialog v-model="scenarioDetailVisible" :title="selectedScenario.name" width="70%" top="5vh">
      <div class="scenario-detail" v-if="selectedScenario.id">
        <el-descriptions border :column="2">
          <el-descriptions-item label="场景类型">
            {{ getScenarioTypeName(selectedScenario.type) }}
          </el-descriptions-item>
          <el-descriptions-item label="适用总线">
            {{ selectedScenario.buses.join(', ') }}
          </el-descriptions-item>
          <el-descriptions-item label="推荐攻击方法" :span="2">
            <el-tag v-for="(tech, index) in selectedScenario.techniques" :key="index" class="tech-tag">
              {{ tech }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ selectedScenario.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ selectedScenario.updateTime || '无' }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="detail-section">
          <h4>场景描述</h4>
          <p>{{ selectedScenario.description }}</p>
        </div>

        <div class="detail-section" v-if="selectedScenario.architecture">
          <h4>系统架构</h4>
          <div class="architecture-image">
            <el-image :src="selectedScenario.architecture" fit="contain"
              :preview-src-list="[selectedScenario.architecture]" />
          </div>
        </div>

        <div class="detail-section">
          <h4>适用方案</h4>
          <base-table :data="selectedScenario.relatedPlans" :border="true" :show-pagination="false">
            <el-table-column prop="name" label="方案名称" min-width="250" />
            <el-table-column prop="type" label="方案类型" width="120" />
            <el-table-column prop="attackType" label="攻击类型" width="150" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="primary" link @click="viewPlan(scope.row)">查看方案</el-button>
              </template>
            </el-table-column>
          </base-table>
        </div>
      </div>
    </el-dialog>

    <!-- 创建场景对话框 -->
    <el-dialog v-model="createDialogVisible" title="添加业务场景" width="60%">
      <el-form ref="scenarioFormRef" :model="scenarioForm" :rules="scenarioRules" label-width="100px"
        style="margin-top: 20px;">
        <el-form-item label="场景名称" prop="scene_name">
          <el-input v-model="scenarioForm.scene_name" placeholder="请输入场景名称" />
        </el-form-item>
        <el-form-item label="适用总线" prop="scene_dbus_type">
          <el-checkbox-group v-model="scenarioForm.scene_dbus_type">
            <el-checkbox v-for="item in busTypeList" :key="item.id" :label="item.bus_type_name"
              :value="item.id"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="场景描述" prop="scene_desc">
          <el-input v-model="scenarioForm.scene_desc" type="textarea" :rows="5" placeholder="请输入场景描述" />
        </el-form-item>
        <!-- <el-form-item label="系统架构图">
          <el-upload class="architecture-upload" action="#" :auto-upload="false" :limit="1" accept="image/*">
            <el-button type="primary">选择图片</el-button>
            <template #tip>
              <div class="el-upload__tip">只能上传 jpg/png 文件，且不超过 5MB</div>
            </template>
          </el-upload>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitScenarioForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 业务场景库页面
 * @file business.vue
 */
import { ref, provide, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import ScenarioCardList from './ScenarioCardList/index.vue'
import SearchForm from '@/components/SearchForm/index.vue'
import BaseTable from '@/components/BaseTable/index.vue'
import { getSceneList, addScene, updateScene, deleteScene } from '@/api/topo/scene'
import { useCommonStore } from '@/stores/common'
const { busTypeList } = useCommonStore()
console.log(busTypeList)

// 搜索表单数据
const searchForm = ref({
  // scene_name: '',
  // type: ''
})

// 状态变量
const loading = ref(false)

// 分页参数
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 场景详情对话框可见性
const scenarioDetailVisible = ref(false)

// 创建场景对话框可见性
const createDialogVisible = ref(false)

// 选中的场景详情
const selectedScenario = ref({})

// 场景表单引用
const scenarioFormRef = ref(null)

// 场景表单数据
const scenarioForm = ref({
  // scene_name: '',
})

// 场景表单验证规则
const scenarioRules = {
  scene_name: [
    { required: true, message: '请输入场景名称', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  scene_dbus_type: [
    { required: true, message: '请选择适用总线', trigger: 'change' }
  ],
  scene_desc: [
    { required: true, message: '请输入场景描述', trigger: 'blur' }
  ]
}

// 业务场景数据
const scenarios = ref([])

/**
 * 获取场景数据
 */
const fetchData = async () => {
  loading.value = true
  const params = {
    page_index: page.value,
    page_size: pageSize.value,
    scene_name: searchForm.value.scene_name
  }

  const { data } = await getSceneList(params)

  // 转换API返回的数据格式为组件需要的格式
  scenarios.value = data.data;
  total.value = data.total || 0
  loading.value = false
}

// 创建场景
const createScenario = () => {
  createDialogVisible.value = true
}

// 提交场景表单
const submitScenarioForm = async () => {
  if (!scenarioFormRef.value) return

  await scenarioFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      // 转换表单数据为API所需格式
      const apiData = {
        scene_name: scenarioForm.value.scene_name,
        scene_desc: scenarioForm.value.scene_desc,
        scene_dbus_type: scenarioForm.value.scene_dbus_type.join(','),
        creator: '' // 实际应用中应使用当前登录用户
      }

      let response
      if (scenarioForm.value.id) {
        // 更新场景
        apiData.id = scenarioForm.value.id
        response = await updateScene(apiData)
      } else {
        // 添加场景
        response = await addScene(apiData)
      }

      ElMessage.success(scenarioForm.value.id ? '场景更新成功' : '场景创建成功')
      createDialogVisible.value = false
      fetchData() // 刷新数据
    } else {
      console.log('表单验证失败:', fields)
      ElMessage.error('表单填写有误，请检查')
    }
  })
}

/**
 * 编辑场景
 * @param {Object} scenario 场景对象
 */
const editScenario = (scenario) => {
  scenarioForm.value = {
    id: scenario.id,
    name: scenario.name,
    type: scenario.type,
    buses: scenario.buses,
    description: scenario.description,
    architecture: scenario.architecture
  }
  createDialogVisible.value = true
}

/**
 * 删除场景
 * @param {number} id 场景ID
 */
const deleteScenarioHandler = async (id, status) => {
  try {
    // 确认删除
    await ElMessageBox.confirm('确定要删除该场景吗？删除后不可恢复', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用删除API
    loading.value = true
    const response = await deleteScene({ id, status })

    if (response && response.code === 200) {
      ElMessage.success('场景删除成功')
      fetchData() // 刷新数据
    } else {
      ElMessage.error(response?.msg || '删除场景失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除场景出错:', error)
      ElMessage.error('删除场景出错')
    }
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  page.value = 1
  fetchData()
}

// 处理重置
const handleReset = () => {
  searchForm.value = {
    scene_name: '',
    type: ''
  }
  handleSearch()
}

// 处理分页
const handlePagination = (pag) => {
  page.value = pag.page
  pageSize.value = pag.limit
  fetchData()
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})


// 获取场景类型名称
const getScenarioTypeName = (type) => {
  const nameMap = {
    drone: '无人机场景',
    industrial: '工业自动化',
    avionics: '航电场景'
  }
  return nameMap[type] || type
}

// 查看方案
const viewPlan = (plan) => {
  const router = useRouter()
  router.push(`/tactical-plan/detail/${plan.id}`)
}

// 场景详情处理函数
const viewScenarioHandler = (scenario) => {
  selectedScenario.value = scenario
  scenarioDetailVisible.value = true
}

// 向子组件提供查看场景的方法
provide('viewScenario', viewScenarioHandler)
provide('editScenario', editScenario)
provide('deleteScenario', deleteScenarioHandler)

/**
 * 处理每页条数变化
 * @param {number} val 新的每页条数
 */
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

/**
 * 处理当前页变化
 * @param {number} val 新的当前页
 */
const handleCurrentChange = (val) => {
  page.value = val
  fetchData()
}

// 处理选项卡点击
const handleTabClick = () => {
  // 切换选项卡时重新加载数据
  fetchData()
}
</script>

<style lang="scss" scoped>
.business-scenarios-container {
  padding: 20px;


    h2 {
      margin: 0;
    }
  

  .scenario-tabs {
    margin-top: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    // justify-content: center;
    justify-content: flex-end;
  }

  .scenario-detail {
    .detail-section {
      margin-top: 20px;

      h4 {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 10px;
        color: #303133;
        position: relative;
        padding-left: 10px;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 3px;
          height: 16px;
          background-color: #409EFF;
          border-radius: 2px;
        }
      }

      p {
        color: #606266;
        line-height: 1.8;
      }

      .architecture-image {
        max-height: 400px;
        display: flex;
        justify-content: center;
        margin: 20px 0;

        .el-image {
          max-height: 100%;
        }
      }

      .tech-tag {
        margin-right: 10px;
        margin-bottom: 5px;
      }
    }
  }
}
</style>